package com.example.demo.security;

import com.example.demo.model.entity.user.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
public class AuthenticationFacade implements IAuthenticationFacade {

    /**
     * 获取当前认证用户的完整用户对象
     * @return 当前用户实体
     * @throws UsernameNotFoundException 如果用户未认证或用户信息不存在
     */
    @Override
    public User getCurrentUser() {
        Authentication authentication = getAuthentication();

        if (authentication == null || !authentication.isAuthenticated()) {
            throw new UsernameNotFoundException("用户未认证");
        }

        Object principal = authentication.getPrincipal();

        if (principal instanceof User) {
            return (User) principal;
        } else if (principal instanceof org.springframework.security.core.userdetails.UserDetails) {
            // 如果principal是UserDetails，可能需要从数据库重新加载完整用户信息
            String username = ((org.springframework.security.core.userdetails.UserDetails) principal).getUsername();
            throw new UsernameNotFoundException("需要从数据库加载用户: " + username);
        } else {
            throw new UsernameNotFoundException("无法识别的用户主体类型");
        }
    }

    /**
     * 获取当前认证用户的用户名
     * @return 用户名
     */
    @Override
    public String getCurrentUsername() {
        Authentication authentication = getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }
        return authentication.getName();
    }

    /**
     * 获取完整的Authentication对象
     * @return Authentication对象
     */
    @Override
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 检查当前用户是否有指定角色
     * @param role 角色名称
     * @return 是否有该角色
     */
    public boolean hasRole(String role) {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return false;
        }
        return authentication.getAuthorities().stream()
                .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals("ROLE_" + role));
    }

    /**
     * 检查当前用户是否是管理员
     * @return 是否是管理员
     */
    public boolean isAdmin() {
        return hasRole("ADMIN");
    }
}